import { load } from 'js-yaml';
import { readFile } from 'fs-extra';
import { isAbsolute, join } from 'path';

/**
 * only for server side
 * get yaml file data
 * @param path when is local: relative path / absolute path,
 *             when is remote: absolute path
 * @param isRemote is remove path
 * @returns yaml data
 */
async function getValueFromYamlAsync<T = any>(path: string, isRemote: boolean): Promise<T> {
    //
    let data = '';
    if (isRemote) {
        //#TODO make this happen
        //axios.get();
    } else {
        let filePath = path;
        if (!isAbsolute(filePath)) {
            filePath = join(__dirname, filePath);
        }

        try {
            data = (await readFile(filePath))?.toString();
        } catch (e) {
            //#TODO make this global
            console.log(e);
        }
    }
    return loadYamlData<T>(data);
}

function loadYamlData<T = any>(data: string) {
    return load(data) as T;
}

export { getValueFromYamlAsync, loadYamlData };
